package net.risesoft.risebi.collection.web.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.model.Query;
import net.risesoft.risebi.collection.model.Role;
import net.risesoft.risebi.collection.model.RoleMember;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.QueryManager;
import net.risesoft.risebi.collection.service.QueryParameterManager;
import net.risesoft.risebi.collection.service.RoleManager;
import net.risesoft.risebi.collection.service.RoleMemberManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
*
* @author <a href="mailto: dingzhaojun2046@hotmail.com">丁兆俊</a>
* @version $Revision$
* 
*/
@Namespace("/admin/RoleAction")
public class RoleAction extends BaseAction {
	private static final long serialVersionUID = 1483053918022813772L;
	private String treeId = "privilege-tree";
	
	private Role role;	
	private User user;	

	private RoleManager roleManager;
	private RoleMemberManager roleMemberManager;
	private QueryManager queryManager;
	private QueryParameterManager queryParameterManager;
	private UserManager userManager;	
	
	private String field; //Ext.ux.plugins.RemoteValidator
	private String value; //Ext.ux.plugins.RemoteValidator
	private String crud;
	private String deletedRoleMember;
	private String addedUser;
	private String serviceGuid;
	
	@Action(value="prepareList4SystemUser",
			results={@Result(name="success", location="/admin/role/roleList4SystemUser.jsp")}
	)
	public String prepareList4SystemUser() throws Exception {
		List lst = queryManager.getObjects(Query.class);
		this.json = JSONUtil.getJsonString("include", "guid,name", lst);	
		this.serviceGuid = "";
		
		return SUCCESS;
	}

	@Action(value="prepareList4ServiceUser",
			results={@Result(name="success", location="/admin/role/roleList4ServiceUser.jsp")}
	)
	public String prepareList4ServiceUser() throws Exception {
		List lst = queryManager.getObjects(Query.class);
		this.json = JSONUtil.getJsonString("include", "guid,name", lst);	
		this.serviceGuid = this.getDefaultService().getGuid();
		
		return SUCCESS;
	}
	
	@Action(value="prepareAdd",
			results={@Result(name="success", location="/admin/role/roleAdd.jsp")}
	)
	public String prepareAdd() throws Exception {
				
		return SUCCESS;
	}

	@Action(value="add")
	public String add() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Double count = (Double)roleManager.getUniqueObject("select max(r.tabIndex) from Role r");
			if(count==null){
				count = new Double(0);
			}

			String guid = new GUID().toString();
			role.setGuid(guid);
			role.setTabIndex(count.intValue()+1.0);
			role.setBuiltIn(false);
			role.setServiceGuid(this.serviceGuid);
			
			roleManager.saveObject(role);		
			
			ldb.set("success", true);
			ldb.set("reason", "增加角色成功!");
			
			ldb.set("guid", guid);
			ldb.set("parentGuid", role.getParentGuid());
			ldb.set("name", role.getName());
			ldb.set("description", role.getDescription());
			ldb.set("type", role.getType());
			ldb.set("dynamic", role.getDynamic());
			ldb.set("queryGuid", role.getQueryGuid());
			ldb.set("policy", role.getPolicy());
			ldb.set("tabIndex", role.getTabIndex());
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="addMember")
	public String addMember() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			//role = (Role)roleManager.getObject(Role.class, role.getGuid());
			String[] userGuid = this.addedUser.split(",");
			List list = new ArrayList();
			int i=0;
			for(String u : userGuid){
				User user = new User();
				user.setGuid(u);
				
				RoleMember rm = new RoleMember();
				String guid = new GUID().toString();
				rm.setGuid(guid);
				rm.setRole(role);
				rm.setUser(user);
				rm.setTabIndex(Integer.valueOf(++i)+0.0);
				
				list.add(rm);
			}
			roleMemberManager.saveObjects(list);
			
			ldb.set("success", true);
			ldb.set("reason", "addRoleMember success!");
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="prepareEdit",
			results={@Result(name="success", location="/admin/role/roleEdit.jsp")}
	)
	public String prepareEdit() throws Exception {
		role = (Role)roleManager.getObject(Role.class, role.getGuid());
		if(role.getDynamic()==null){
			role.setDynamic(false);
		}
		if(role.getPolicy()==null){
			role.setPolicy(false);
		}
		
		List lst = queryManager.getObjects(Query.class);
		this.json = JSONUtil.getJsonString("include", "guid,name", lst);	

		return SUCCESS;
	}

	@Action(value="prepareMember",
			results={@Result(name="success", location="/admin/role/roleMember.jsp")}
	)
	public String prepareMember() throws Exception {
		
		return SUCCESS;
	}

	@Action(value="prepareMemberAdd",
			results={@Result(name="success", location="/admin/role/roleMemberAdd.jsp")}
	)
	public String prepareMemberAdd() throws Exception {
		
		return SUCCESS;
	}

	@Action(value="edit")
	public String edit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if(role.getDynamic()==null){
				role.setDynamic(false);
			}
			if(role.getPolicy()==null){
				role.setPolicy(false);
			}

			if(role.getService()==null || role.getServiceGuid().trim().length()==0){
				role.setServiceGuid(this.serviceGuid);
			}
			
			roleManager.saveObject(role);	
			
			ldb.set("success", true);
			ldb.set("reason", "修改角色成功。");
			
			ldb.set("guid", role.getGuid());
			ldb.set("parentGuid", role.getParentGuid());
			ldb.set("name", role.getName());
			ldb.set("description", role.getDescription());
			ldb.set("type", role.getType());
			ldb.set("dynamic", role.getDynamic());
			ldb.set("queryGuid", role.getQueryGuid());
			ldb.set("policy", role.getPolicy());
			ldb.set("tabIndex", role.getTabIndex());
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			roleManager.removeObject(Role.class, role.getGuid()); 		
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功！");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="removeMember")
	public String removeMember() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if("allRoleMembers".equals(this.deletedRoleMember)){
				roleMemberManager.execute("delete from RoleMember rm where rm.role.guid='" + role.getGuid() + "'");
			}else{
				roleMemberManager.removeObject(RoleMember.class, this.deletedRoleMember);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功！");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	@Action(value="validateRoleName")
	public String validateRoleName() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();		
		try{			
			if("c".equals(this.crud)){
				List lst = roleManager.find("from Role r where r.name='" + this.value + "' and r.service.guid='" + this.serviceGuid + "'");
				if(lst.size()>0){
					ldb.set("success", true);
					ldb.set("valid", false);
					ldb.set("reason", "名称重复。");
					this.json = JSONObject.fromObject(ldb).toString();
					
					return AJAX;
				}
			}else{
				List lst = roleManager.find("from Role r where r.name='" + this.value + "' and r.service.guid='" + this.serviceGuid + "' and r.guid !='" + role.getGuid() + "'");
				if(lst.size()>0){
					ldb.set("success", true);
					ldb.set("valid", false);
					ldb.set("reason", "名称重复。");
					this.json = JSONObject.fromObject(ldb).toString();
					
					return AJAX;
				}
			}
			
			ldb.set("success", true);
			ldb.set("valid", true);
			ldb.set("reason", "名称不重复，可以使用。");
			this.json = JSONObject.fromObject(ldb).toString();			
		}catch(Exception e){
			ldb.set("success", true);
			ldb.set("valid", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();			
		}
		
		return AJAX;		
	}

	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonQuerys".equalsIgnoreCase(this.whichJson)){
				List lst = queryManager.getObjects(Query.class);
				this.json = JSONUtil.getJsonString("include", "guid,name", lst);					
			}else if("jsonAllQuerys".equalsIgnoreCase(this.whichJson)){
				List lst = queryManager.getObjects(Query.class);
				this.json = JSONUtil.getJsonString("exclude", "params", lst);									
			}else if("jsonRoleMembers".equalsIgnoreCase(this.whichJson)){
				role = (Role)roleManager.getObject(Role.class, role.getGuid());
				this.json = JSONUtil.getJsonString("include", "guid,userGuid,loginName,realName,enabled,tabIndex", role.getRoleMembers());									
			}else if("jsonUsers".equalsIgnoreCase(this.whichJson)){
				Map map = null;
				String filter = "";
				if(this.user==null) user = new User();
				if(this.source != null && this.source.equalsIgnoreCase("so")){
					user.setUserType(2);
				}else if(this.source != null && this.source.equalsIgnoreCase("manager")){
					user.setUserType(1);
				}
				filter = "u.guid not in (select rm.user from RoleMember rm where rm.role.guid='" + role.getGuid() + "')";
				map = userManager.getAllUser(user, "u", filter, start, limit);
				this.json = JSONUtil.getJsonString("include", "count,list,guid,name,realName,enabled,authentication_type,userType,openAccountType,tabIndex", map);
			}else if("jsonUsers4RoleMember".equalsIgnoreCase(this.whichJson)){
				if(this.user==null) user = new User();				
				user.setUserType(User.USERTYPE_SYSTEMMANAGER);
				String filter = "u.guid not in (select rm.user.guid from RoleMember rm where rm.role.guid='" + role.getGuid() + "')";
				Map map = userManager.getAllUser(user, "u", filter, start, limit);
				this.json = JSONUtil.getJsonString("include", "count,list,guid,name,realName,enabled,tabIndex", map);
			}else if("jsonRoles4SystemUser".equalsIgnoreCase(this.whichJson)){
				String hql = "from Role r where r.service is null or trim(r.service.guid)=''";
				List<Role> lst = roleManager.find(hql);
				this.json = JSONUtil.getJsonString("exclude", "parentRole,query,roleMembers,service", lst);
			}else if("jsonRoles4ServiceUser".equalsIgnoreCase(this.whichJson)){
				String hql = "from Role r where r.service.guid='" + this.getDefaultService().getGuid() + "'";
				List<Role> lst = roleManager.find(hql);
				this.json = JSONUtil.getJsonString("exclude", "parentRole,query,roleMembers,service", lst);
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		}
		return AJAX;
	}

	/**
     * A default implementation that validates nothing.
     * Subclasses should override this method to provide validations.
     */
    public void validate() {
    }

	public String getTreeId() {
		return treeId;
	}

	public void setTreeId(String treeId) {
		this.treeId = treeId;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public RoleMemberManager getRoleMemberManager() {
		return roleMemberManager;
	}

	public void setRoleMemberManager(RoleMemberManager roleMemberManager) {
		this.roleMemberManager = roleMemberManager;
	}

	public QueryManager getQueryManager() {
		return queryManager;
	}

	public void setQueryManager(QueryManager queryManager) {
		this.queryManager = queryManager;
	}

	public QueryParameterManager getQueryParameterManager() {
		return queryParameterManager;
	}

	public void setQueryParameterManager(QueryParameterManager queryParameterManager) {
		this.queryParameterManager = queryParameterManager;
	}

	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getCrud() {
		return crud;
	}

	public void setCrud(String crud) {
		this.crud = crud;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public String getDeletedRoleMember() {
		return deletedRoleMember;
	}

	public void setDeletedRoleMember(String deletedRoleMember) {
		this.deletedRoleMember = deletedRoleMember;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public String getAddedUser() {
		return addedUser;
	}

	public void setAddedUser(String addedUser) {
		this.addedUser = addedUser;
	}
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getServiceGuid() {
		return serviceGuid;
	}

	public void setServiceGuid(String serviceGuid) {
		this.serviceGuid = serviceGuid;
	}

}
